package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.redis.key.RedisKeys;
import cn.wolfcode.luowowo.redis.redisService.ISecurityRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.RequestUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防刷拦截器
 */
//@Component
public class BrushProofInterceptor implements HandlerInterceptor {
    @Autowired
    private ISecurityRedisService securityRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //如果不是动态请求 放行
        if(!(handler instanceof HandlerMethod)){
            return  true;
        }
        //请求接口 url
        String url = request.getRequestURI().substring(1);
        //请求的ip地址
        String ip = RequestUtil.getIPAddress();
        //拼接key
        String key = RedisKeys.BRUSH_PROOF.join(url, ip);

        if(!securityRedisService.isAllowBrush(key)){
            //如果返回的是false 表示已超出频率
            //可做额外出来 加进黑名单
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(
                    JsonResult.error(500, "请勿频繁访问","谢谢咯")));
            return false;
        }
        return true;
    }
}